﻿''' <summary>
''' 主キー属性
''' </summary>
''' <remarks>
''' 列属性ではありません
''' </remarks>
<AttributeUsage(AttributeTargets.Property)>
Public Class KeyAttribute
    Inherits Attribute

    Private _Column As ColumnAttribute
    Public Property Column() As ColumnAttribute
        Get
            Return _Column
        End Get
        Set(ByVal value As ColumnAttribute)
            _Column = value
            If _Column IsNot Nothing Then Me.Initialize(_Column)
        End Set
    End Property

    Protected Overridable Sub Initialize(col As ColumnAttribute)
        'Load関数を差し替える
        col.KeyLoadWhereCommandBuilder = AddressOf Me.CreateLoadWhereCommand
        col.ReLoadWhereCommandCreater = AddressOf Me.CreateLoadWhereCommand

        'Save関数を差し替える
        col.DirtyChecker = Function() False
        col.SaveWhereCommandCreater = AddressOf Me.CreateSaveWhereCommand
        col.UpdateColumnCommandCreater = Nothing
    End Sub

    Protected Sub CreateLoadWhereCommand(value As Object, sqlBuilder As Action(Of String), paramRegister As Func(Of Object, String))
        Dim pname As String = paramRegister.Invoke(value)
        sqlBuilder.Invoke(String.Format("{0} = {1}", Me.Column.ColumnName, pname))
    End Sub

    Protected Sub CreateSaveWhereCommand(instance As Object, archiveValue As Object, sqlBuilder As Action(Of String), paramRegister As Func(Of Object, String))
        Dim pname As String = paramRegister.Invoke(archiveValue)
        sqlBuilder.Invoke(String.Format("{0} = {1}", Me.Column.ColumnName, pname))
    End Sub

    ''' <summary>
    ''' 事前に主キーを取得するコマンドを生成します
    ''' </summary>
    ''' <param name="trn"></param>
    ''' <returns></returns>
    ''' <remarks>サポートしていない場合、Nothingが返されます</remarks>
    Public Overridable Function CreateKeyQueryBeforeSave(trn As IDbTransaction) As IDbCommand
        Return Nothing
    End Function

    ''' <summary>
    ''' 事後に主キーを取得するコマンドを生成します
    ''' </summary>
    ''' <param name="trn"></param>
    ''' <returns></returns>
    ''' <remarks>サポートしていない場合、Nothingが返されます</remarks>
    Public Overridable Function CreateKeyQueryAfterSave(trn As IDbTransaction) As IDbCommand
        Return Nothing
    End Function

End Class
